package org.wishwork.api.product.combine.query;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.wishwork.api.Api;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 组合装商品查询
 * @author: WangYX
 * @create: 2022-04-11 15:39
 * @Version: 1.0.0
 **/

public class CombineProductQueryApi extends Api<List<CombineProductQueryResponse>, CombineProductQueryRequest> {

    private Context context;

    public CombineProductQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(CombineProductQueryRequest combineProductQueryRequest) throws Exception {
        String url = "/open/combine/sku/query";
        Map<String, Object> params = new HashMap<>();
        if (StrUtil.isNotEmpty(combineProductQueryRequest.getSkuIds())) {
            params.put("sku_ids", combineProductQueryRequest.getSkuIds());
        }
        return HttpHelper.sendRequest(combineProductQueryRequest, params, url);
    }

    @Override
    protected List<CombineProductQueryResponse> process(JSONObject data, CombineProductQueryRequest combineProductQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<CombineProductQueryResponse> combineProductQueryResponses = datas.toJavaList(CombineProductQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = combineProductQueryRequest.getPageIndex();
            CombineProductQueryRequest build = combineProductQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<CombineProductQueryResponse> business = business(build);
            combineProductQueryResponses.addAll(business);
        }
        return combineProductQueryResponses;
    }
}
